import os

from DrissionPage import Chromium
from loguru import logger

import config
from lib.util import io_utils
from lib.util.version_utils import compare_version


# MySQL下载地址，只能使用cdn域名下载，其他域名会重定向到cdn域名，程序不能直接下载
#
# https://dev.mysql.com/get/Downloads/MySQL-9.3/mysql-9.3.0-winx64.zip
# https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-8.4.5-winx64.zip
# https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.42-winx64.zip
#
# https://dev.mysql.com/get/Downloads/MySQL-9.2/mysql-9.2.0-winx64.zip
# https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-5.7.9-winx64.zip
#
# https://downloads.mysql.com/archives/get/p/23/file/mysql-9.2.0-winx64.zip
# https://downloads.mysql.com/archives/get/p/23/file/mysql-8.4.4-winx64.zip
# https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.9-winx64.zip
# https://cdn.mysql.com/archives/mysql-8.4/mysql-8.4.4-winx64.zip
#
# https://cdn.mysql.com/Downloads/MySQL-9.3/mysql-9.3.0-winx64.zip


def fetch_mysql_versions(browser: Chromium):
    """
    抓取MySQL版本列表
    :param browser:
    :return:
    """
    try:
        tab = browser.new_tab()

        # 获取最新稳定版本
        logger.debug("获取MySQL最新版本列表...")
        tab.get('https://dev.mysql.com/downloads/mysql/')
        version_select = tab.ele("@name=version")
        version_options = version_select.eles("tag:option")
        latest_versions = list()
        for it in version_options:
            minor_version = it.attr("value")
            version = it.text
            if ' ' in version:
                # 有些版本号上代字母
                [version_value, _] = version.split(' ')
            else:
                version_value = version
            latest_versions.append({
                'version': version_value,
                'name': version,
                'url': f'https://cdn.mysql.com/Downloads/MySQL-{minor_version}/mysql-{version_value}-winx64.zip'
            })

        logger.debug(f"获取MySQL最新版本列表... {len(latest_versions)}条")
        latest_file_path = os.path.join(config.base_dir, "data/mysql-latest.json")
        io_utils.write_json(latest_file_path, {'versions': latest_versions})
        logger.debug(f"保存到最新版本数据到: {latest_file_path}")

        # 获取历史版本
        logger.debug("获取MySQL历史版本列表...")
        tab.get("https://downloads.mysql.com/archives/community/")
        version_select = tab.ele("@name=version")
        version_options = version_select.eles("tag:option")
        history_versions = list()
        for it in version_options:
            version = it.attr("value")
            # 判断版本号小于5.7.9的不要
            if compare_version(version, "5.7.9") < 0:
                continue
            label = it.text
            version_in_path = label.replace(' ', '-')
            version_tokens = version.split('.')
            short_version = f'{version_tokens[0]}.{version_tokens[1]}'
            history_versions.append({
                'version': version,
                'name': label,
                'url': f'https://cdn.mysql.com/archives/mysql-{short_version}/mysql-{version_in_path}-winx64.zip'
            })

        logger.debug(f"获取MySQL历史版本列表... {len(history_versions)}条")

        history_file_path = os.path.join(config.base_dir, "data/mysql-history.json")
        io_utils.write_json(history_file_path, {'versions': history_versions})
        logger.debug(f"保存历史数据到: {history_file_path}")
    except Exception:
        logger.exception("获取MySQL版本列表失败")
    finally:
        tab and tab.close()
